import { ModernBaseService } from './base/ModernBaseService';
import { MarketRepository, MarketItem, MarketLog } from '../repository/MarketRepository';
import { Item } from '../shared/face';
import { ItemType, 资源枚举 } from '../shared/face/enums';
import MailManage from '../core/manage/MailManage';
import bag_component from '../component/bag_component';
import { ComType } from '../core/tool/component';

/**
 * 现代化市场服务 - 统一管理市场交易
 */
export class ModernMarketService extends ModernBaseService {
    private _marketRepository?: MarketRepository;

    constructor(container?: any) {
        super(container);
    }

    /**
     * 懒加载市场仓储
     */
    private get marketRepository(): MarketRepository {
        if (!this._marketRepository) {
            this._marketRepository = this.getService<MarketRepository>('MarketRepository');
        }
        return this._marketRepository;
    }

    /**
     * 初始化市场服务
     */
    async initialize(): Promise<void> {
        try {
            this.log('正在初始化现代化市场服务...');
            
            // 初始化市场仓储
            await this.marketRepository.initialize();
            
            this.log('现代化市场服务初始化完成');
        } catch (error) {
            this.log('现代化市场服务初始化失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    // ============ 市场商品管理 ============

    /**
     * 上架商品
     * @param item 道具
     * @param price 价格
     * @param sellerId 卖家ID
     * @returns 商品ID
     */
    async putOnSale(item: Item, price: number, sellerId: string): Promise<string> {
        this.validateRequiredParams({ item, price, sellerId }, ['item', 'price', 'sellerId']);
        
        try {
            const marketItemId = await this.marketRepository.putItemOnSale(item, price, sellerId);
            this.log(`商品上架成功: ${item.name} 价格: ${price} 卖家: ${sellerId}`);
            return marketItemId;
        } catch (error) {
            this.log('上架商品失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 下架商品
     * @param itemId 商品ID
     * @param sellerId 卖家ID
     * @returns 是否成功
     */
    async takeOffSale(itemId: string, sellerId: string): Promise<boolean> {
        this.validateRequiredParams({ itemId, sellerId }, ['itemId', 'sellerId']);
        
        try {
            const success = await this.marketRepository.takeOffSale(itemId, sellerId);
            if (success) {
                this.log(`商品下架成功: ${itemId} 卖家: ${sellerId}`);
            }
            return success;
        } catch (error) {
            this.log('下架商品失败: ' + (error as any).message, 'error');
            return false;
        }
    }

    /**
     * 购买商品
     * @param itemId 商品ID
     * @param buyer 买家对象
     * @param count 购买数量
     * @returns 错误信息，null表示成功
     */
    async buy(itemId: string, buyer: any, count: number): Promise<string | null> {
        this.validateRequiredParams({ itemId, buyer, count }, ['itemId', 'buyer', 'count']);
        
        try {
            const item = await this.marketRepository.getItemInfo(itemId);
            if (!item) {
                this.log(`商品不存在: ${itemId}`, 'warn');
                return '商品不存在';
            }

            if (item.item.count < count) {
                count = item.item.count;
            }

            // 检查买家金币是否足够
            const bagCom = buyer.getComponent(ComType.背包) as bag_component;
            const buyerGold = bagCom.goldBuy(item.sell_price * count);
            if (!buyerGold) {
                this.log(`买家金币不足: ${buyer.id} 需要: ${item.sell_price * count}`, 'warn');
                return '金币不足';
            }

            // 给买家添加商品
            let buyItem = JSON.parse(JSON.stringify(item.item));
            buyItem.count = count;
            await MailManage.send(
                'admin', 
                buyer.id, 
                30, 
                '交易所·购买完成', 
                `您已购买 ${buyItem.name}x${buyItem.count}`, 
                [buyItem]
            );

            // 给卖家添加金币
            let sellItem = this.sdk.prop.createProp({ 
                type: ItemType.资源, 
                id: 资源枚举.金币, 
                count: item.sell_price * buyItem.count 
            });
            await MailManage.send(
                'admin', 
                item.put_id, 
                30, 
                '交易所·出售完成', 
                `您的商品 ${item.item.name}x${buyItem.count} 已售出，获得 ${item.sell_price * buyItem.count} 金币`, 
                [sellItem]
            );

            // 记录交易日志
            await this.marketRepository.recordTrade(item, buyer.id, item.put_id, item.sell_price);

            // 从市场移除商品（更新状态）
            await this.marketRepository.removeFromMarket(itemId, count);

            this.log(`商品成交: ${item.item.name} 买家: ${buyer.id} 卖家: ${item.put_id}`);
            return null; // 成功
        } catch (error) {
            this.log('购买商品失败: ' + (error as any).message, 'error');
            return '购买失败';
        }
    }

    // ============ 数据访问 ============

    /**
     * 获取市场商品列表
     */
    async getMarketItems(): Promise<MarketItem[]> {
        try {
            return await this.marketRepository.getMarketItems();
        } catch (error) {
            this.log('获取市场商品列表失败: ' + (error as any).message, 'error');
            return [];
        }
    }

    /**
     * 获取市场日志
     */
    async getMarketLogs(): Promise<MarketLog[]> {
        try {
            return await this.marketRepository.getMarketLogs();
        } catch (error) {
            this.log('获取市场日志失败: ' + (error as any).message, 'error');
            return [];
        }
    }

    /**
     * 获取商品信息
     */
    async getItemInfo(itemId: string): Promise<MarketItem | undefined> {
        this.validateRequiredParams({ itemId }, ['itemId']);
        
        try {
            return await this.marketRepository.getItemInfo(itemId);
        } catch (error) {
            this.log('获取商品信息失败: ' + (error as any).message, 'error');
            return undefined;
        }
    }

    /**
     * 按条件搜索市场商品
     */
    async searchMarketItems(criteria: {
        sellerId?: string;
        minPrice?: number;
        maxPrice?: number;
        itemType?: string;
        itemName?: string;
    }): Promise<MarketItem[]> {
        try {
            return await this.marketRepository.searchMarketItems(criteria);
        } catch (error) {
            this.log('搜索市场商品失败: ' + (error as any).message, 'error');
            return [];
        }
    }

    /**
     * 获取市场统计信息
     */
    async getMarketStats(): Promise<{
        totalItems: number;
        totalTransactions: number;
        averagePrice: number;
        topSellers: Array<{ sellerId: string; itemCount: number }>;
        recentTransactions: MarketLog[];
    }> {
        try {
            return await this.marketRepository.getMarketStats();
        } catch (error) {
            this.log('获取市场统计信息失败: ' + (error as any).message, 'error');
            return {
                totalItems: 0,
                totalTransactions: 0,
                averagePrice: 0,
                topSellers: [],
                recentTransactions: []
            };
        }
    }

    // ============ 数据持久化 ============

    /**
     * 保存市场数据到数据库
     */
    async save(): Promise<void> {
        try {
            await this.marketRepository.save();
            this.log('市场数据保存成功');
        } catch (error) {
            this.log('保存市场数据失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    // ============ 兼容性方法 ============

    /**
     * 兼容旧接口：简化的上架方法
     */
    async put(item: Item, user_id: string, price: number): Promise<string> {
        return await this.putOnSale(item, price, user_id);
    }

    /**
     * 兼容旧接口：获取商品列表
     */
    get list(): Promise<MarketItem[]> {
        return this.getMarketItems();
    }

    /**
     * 兼容旧接口：获取商品类型列表
     */
    async itemListType(): Promise<any[]> {
        try {
            const items = await this.getMarketItems();
            return items.map(item => ({
                id: item._id,
                name: item.item.name,
                price: item.sell_price,
                seller: item.put_id,
                putTime: item.put_time
            }));
        } catch (error) {
            this.log('获取商品类型列表失败: ' + (error as any).message, 'error');
            return [];
        }
    }

    // ============ 批量操作 ============

    /**
     * 批量上架商品
     */
    async batchPutOnSale(items: Array<{
        item: Item;
        price: number;
        sellerId: string;
    }>): Promise<string[]> {
        this.validateRequiredParams({ items }, ['items']);
        
        const results: string[] = [];
        
        for (const { item, price, sellerId } of items) {
            try {
                const marketItemId = await this.putOnSale(item, price, sellerId);
                results.push(marketItemId);
            } catch (error) {
                this.log(`批量上架商品失败: ${item.name} - ${(error as any).message}`, 'error');
            }
        }
        
        this.log(`批量上架商品完成: ${results.length}/${items.length} 件成功`);
        return results;
    }

    /**
     * 批量下架商品
     */
    async batchTakeOffSale(itemIds: string[], sellerId: string): Promise<boolean[]> {
        this.validateRequiredParams({ itemIds, sellerId }, ['itemIds', 'sellerId']);
        
        const results: boolean[] = [];
        
        for (const itemId of itemIds) {
            try {
                const success = await this.takeOffSale(itemId, sellerId);
                results.push(success);
            } catch (error) {
                this.log(`批量下架商品失败: ${itemId} - ${(error as any).message}`, 'error');
                results.push(false);
            }
        }
        
        const successCount = results.filter(r => r).length;
        this.log(`批量下架商品完成: ${successCount}/${itemIds.length} 件成功`);
        return results;
    }

    // ============ 定时任务支持 ============

    /**
     * 清理过期商品
     */
    async cleanupExpiredItems(expireDays: number = 30): Promise<number> {
        try {
            const items = await this.marketRepository.getMarketItems();
            const expireTime = Date.now() - (expireDays * 24 * 60 * 60 * 1000);
            
            let cleanedCount = 0;
            
            for (const item of items) {
                if (item.put_time < expireTime) {
                    const success = await this.marketRepository.takeOffSale(item._id, item.put_id);
                    if (success) {
                        cleanedCount++;
                    }
                }
            }
            
            this.log(`清理过期商品完成: ${cleanedCount} 件商品已过期下架`);
            return cleanedCount;
        } catch (error) {
            this.log('清理过期商品失败: ' + (error as any).message, 'error');
            return 0;
        }
    }
}
